//
//  API.m
//  Test
//
//  Created by 祝文博 on 15/3/9.
//  Copyright (c) 2015年 KevinLab. All rights reserved.
//

#import "API.h"
#import "CocoaSecurity.h"

NSString * const AppKey = @"123";
NSString * const AppSecret = @"abc";
NSString * const DianpingApiBaseUrl = @"http://api.dianping.com";

@implementation API

+ (instancetype)sharedAPI
{
    static id sharedInstance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (void)getPath:(NSString *)path params:(NSDictionary *)params resultBlock:(void (^)(id, NSError *))resultBlock
{
    [self requestWithMethod:@"GET" path:path params:params resultBlock:resultBlock];
}

- (void)requestWithMethod:(NSString *)method path:(NSString *)path params:(NSDictionary *)params resultBlock:(void (^)(id, NSError *))resultBlock
{
    NSDictionary *signedParams = [self signParams:params];
    NSMutableURLRequest *request = [self.requestSerializer
                                    requestWithMethod:method
                                    URLString:[[NSURL URLWithString:path relativeToURL:[NSURL URLWithString:DianpingApiBaseUrl]] absoluteString]
                                    parameters:signedParams
                                    error:nil];
    request.timeoutInterval = 10;
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"\nRequestURL: %@", [operation.request.URL absoluteString]);
//        NSLog(@"\nResponseObject: %@", responseObject);
//        NSLog(@"Headers: %@", operation.response.allHeaderFields);
        
        if ([responseObject isKindOfClass:[NSDictionary class]] == NO) {
            responseObject = nil;
        }
        if ([responseObject[@"status"] isEqualToString:@"OK"]) {
            if (resultBlock) {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    resultBlock(responseObject, nil);
                });
            }
        } else {
            NSLog(@"errorCode : %@, errorMsg : %@", responseObject[@"error"][@"errorCode"], responseObject[@"error"][@"errorMessage"]);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"Error: %@", error);
    }];
    
    [self.operationQueue addOperation:operation];
}

- (NSDictionary *)signParams:(NSDictionary *)params
{
    //参数按照key排序，算SHA-1需要用
    NSArray *allKeys = [params allKeys];
    NSArray *sortedAllKeys = [allKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return [obj1 compare:obj2 options:NSCaseInsensitiveSearch];
    }];
    NSMutableString *sortedParamsStr = [NSMutableString string];
    //拼接前缀appKey
    [sortedParamsStr appendString:AppKey];
    for (NSString *key in sortedAllKeys) {
        [sortedParamsStr appendString:key];
        [sortedParamsStr appendString:[params objectForKey:key]];
    }
    //拼接后缀appSecret
    [sortedParamsStr appendString:AppSecret];
    
    CocoaSecurityResult *signResult = [CocoaSecurity sha1:sortedParamsStr];
    NSString *sign = signResult.hex;
    
    NSMutableDictionary *signedParams = [params mutableCopy];
    [signedParams setObject:AppKey forKey:@"appkey"];
    [signedParams setObject:sign forKey:@"sign"];
    
    return signedParams;
}

@end
